<script setup>

import {ArrowLeftBold, Location, Plus} from "@element-plus/icons-vue";
import router from "@/router";
import {nextTick, reactive, ref} from 'vue'
import {getCurMerchant} from "@/api/merchant";
import {ElMessageBox} from "element-plus";
import {insertANewStore} from "@/api/store";

// 获取当前商家信息
const curMerchant = ref({})
// 动态标签
const dynamicTags = ref([])
const inputVisible = ref(false)
const inputValue = ref('')
const InputRef = ref()
// 店铺封面
const storeCoverImageUrl = ref('')
// 营业执照
const storeLicenseImageUrl = ref('')
// 店铺照片
const storePhotoList = ref([])
// 营业时间
const openingHours = ref([])
// 类别
const categoriesOptions = [
  {
    value: '美食', label: '美食',
    children: [
      {value: '川菜', label: '川菜'},
      {value: '粤菜', label: '粤菜'},
      {value: '湘菜', label: '湘菜'},
      {value: '火锅', label: '火锅'},
      {value: '烧烤', label: '烧烤'},
      {value: '日料', label: '日料'},
      {value: '韩餐', label: '韩餐'},
      {value: '小吃快餐', label: '小吃快餐'},
      {value: '西餐', label: '西餐'},
      {value: '甜品', label: '甜品'},
    ],
  },
  {
    value: '饮品', label: '饮品',
    children: [
      {value: '咖啡', label: '咖啡'},
      {value: '奶茶', label: '奶茶'},
      {value: '果汁', label: '果汁'},
      {value: '冰淇淋', label: '冰淇淋'},
    ],
  },
  {
    value: '购物', label: '购物',
    children: [
      {value: '百货商场', label: '百货商场'},
      {value: '超市便利', label: '超市便利'},
      {value: '服装鞋包', label: '服装鞋包'},
      {value: '化妆品', label: '化妆品'},
      {value: '数码家电', label: '数码家电'},
      {value: '母婴用品', label: '母婴用品'},
      {value: '家具家居', label: '家具家居'},
    ],
  },
  {
    value: '娱乐', label: '娱乐',
    children: [
      {value: '电影院', label: '电影院'},
      {value: 'KTV', label: 'KTV'},
      {value: '密室逃脱', label: '密室逃脱'},
      {value: '桌游', label: '桌游'},
      {value: '电玩城', label: '电玩城'},
      {value: '剧本杀', label: '剧本杀'},
    ],
  },
  {
    value: '酒店', label: '酒店',
    children: [
      {value: '经济型', label: '经济型'},
      {value: '商务型', label: '商务型'},
      {value: '豪华型', label: '豪华型'},
      {value: '民宿客栈', label: '民宿客栈'},
      {value: '青年旅舍', label: '青年旅舍'},
      {value: '度假村', label: '度假村'},
    ],
  },
  {
    value: '景点', label: '景点',
    children: [
      {value: '公园', label: '公园'},
      {value: '博物馆', label: '博物馆'},
      {value: '古镇古村', label: '古镇古村'},
      {value: '游乐园', label: '游乐园'},
      {value: '海滩', label: '海滩'},
      {value: '山地景区', label: '山地景区'},
      {value: '动物园', label: '动物园'},
    ],
  },
  {
    value: '运动', label: '运动',
    children: [
      {value: '健身房', label: '健身房'},
      {value: '游泳馆', label: '游泳馆'},
      {value: '篮球馆', label: '篮球馆'},
      {value: '羽毛球馆', label: '羽毛球馆'},
      {value: '网球馆', label: '网球馆'},
      {value: '瑜伽', label: '瑜伽'},
      {value: '攀岩', label: '攀岩'},
      {value: '滑冰滑雪', label: '滑冰滑雪'},
    ],
  },
  {
    value: '其他', label: '其他',
    children: [
      {value: '宠物', label: '宠物'},
      {value: '医疗健康', label: '医疗健康'},
      {value: '教育培训', label: '教育培训'},
      {value: '生活服务', label: '生活服务'},
    ],
  },
];

// 规则相关
const ruleFormRef = ref()
const ruleForm = reactive({
  storeName: '', // 乐玩电玩城
  categories: [], // ['娱乐', '电玩城']
  storeCover: storeCoverImageUrl,
  storeOpeningTime: '',
  storeContact: '', // 18888888888
  storeAddress: '', // 西安市碑林区aa路bb号
  storeLocation: '',
  storeLicense: storeLicenseImageUrl,
  storePhotos: storePhotoList,
  priceMin: '', // 50
  priceMax: '', // 500
  storeDescription: '', // 这是一家好玩的电玩城！
})
// 规则
const rules = reactive({
  storeName: [
    {required: true, message: '店名不能为空', trigger: 'blur'},
    {min: 2, max: 20, message: '店名长度要在2~20个字之间', trigger: 'blur'},
  ],
  categories: [
    {
      required: true,
      message: '请选择店铺类别',
      trigger: 'blur',
    }
  ],
  storeCover: [
    {
      required: true,
      message: '请上传店铺封面',
      trigger: 'change',
    }
  ],
  storeOpeningTime: [
    {
      required: true,
      message: '请选择营业时间',
      trigger: 'change',
    }
  ],
  storeContact: [
    {
      required: true,
      message: '请输入联系方式',
      trigger: 'blur',
    },
  ],
  storeAddress: [
    {
      required: true,
      message: '请输入详细地址',
      trigger: 'blur',
    }
  ],
  storeLocation: [
    {
      required: true,
      message: '请点击获取店铺位置',
      trigger: 'change',
    }
  ],
  storeLicense: [
    {
      required: true,
      message: '请上传营业执照',
      trigger: 'change',
    }
  ],
  storePhotos: [
    {
      required: true,
      message: '请上传店铺照片',
      trigger: 'change',
    }
  ],
  priceMin: [
    {
      required: true,
      message: '请输入最低价',
      trigger: 'blur',
    },
  ],
  priceMax: [
    {
      required: true,
      message: '请输入最高价',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (value <= ruleForm.priceMin) {
          callback(new Error('最高价必须大于最低价'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    }
  ],
  storeDescription: [
    {
      required: true,
      message: '请输入店铺描述',
      trigger: 'blur',
    }
  ],
})

// 新店铺
const newStore = ref({
  merchantId: '', // 商户ID
  name: '', // 店铺名称
  category: '', // 店铺类别
  subCategory: '', // 子类别
  tags: '', // 店铺标签
  description: '', // 店铺描述
  coverImage: '', // 店铺封面图片
  openingHours: '', // 营业时间
  contactInfo: '', // 联系方式
  address: '', // 店铺地址
  longitude: null, // 经度
  latitude: null,  // 纬度
  status: 0, // 新店铺都是待审核。0: 待审核, 1: 审核通过, 2: 审核不通过
  license: '', // 营业执照图片
  photos: [], // 店铺照片列表
  joinedAt: new Date().toISOString().split('T')[0], // 获取当前日期作为入驻日期, // 入驻日期
  priceMin: '', // 最低价
  priceMax: '', // 最高价
})

// 获取当前商家信息
const getCurMerchantInfo = () => {
  getCurMerchant().then(res => {
    if (res.data) {
      curMerchant.value = res.data
      } else {
      ElMessageBox.alert('请先登录商家账号', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        router.push({path: '/merchantLoginPage'})
      })
    }
  })
}
getCurMerchantInfo()

// 删除一个标签
const handleClose = (tag) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}
//添加新标签时显示输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value?.input?.focus()
  })
}
const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}
// 上传店铺封面
const handleCoverSuccess = (response, uploadFile) => {
  // storeCoverImageUrl.value = URL.createObjectURL(uploadFile.raw)
  storeCoverImageUrl.value = response.data.url
}
// 上传营业执照
const handleLicenseSuccess = (response, uploadFile) => {
  // storeLicenseImageUrl.value = URL.createObjectURL(uploadFile.raw)
  storeLicenseImageUrl.value = response.data.url
}
// 上传店铺照片
const handlePhotoSuccess = (response, uploadFile) => {
  // const storePhotoListLength = storePhotoList.value.length
  // storePhotoList.value[storePhotoListLength] = URL.createObjectURL(uploadFile.raw)
  storePhotoList.value.push(response.data.url)
  console.log(storePhotoList.value)
  // console.log(ruleForm.categories)
  // console.log(newStore.value.category)
  // console.log(newStore.value.subCategory)
  // console.log(Date.now())
  // console.log(new Date().toISOString().split('T')[0])
}

// 提取时间部分并格式化
function formatTime(timeStr) {
  const date = new Date(timeStr);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
}

// 店铺位置（单独设置）
const storeLatitude = ref(null) // 纬度
const storeLongitude = ref(null) // 经度

// 获取位置
const getLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      const lat = position.coords.latitude; // 维度（浮点数）
      const lng = position.coords.longitude; // 经度（浮点数）
      ruleForm.storeLocation = `纬度: ${lat}, 经度: ${lng}`;
      storeLatitude.value = lat; // 存储纬度
      storeLongitude.value = lng; // 存储经度
      ElMessageBox.alert(`位置已获取: ${ruleForm.storeLocation}`, '提示', {
        confirmButtonText: '确定',
        type: 'info'
      }).then(res => {
        // 这里可以将位置存储到新店铺对象中
        newStore.location = ruleForm.storeLocation;
        console.log(newStore.location)
      });
    }, (error) => {
      console.error('获取位置失败:', error);
      ElMessageBox.alert('无法获取位置信息，请检查浏览器权限设置', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      });
    });
  } else {
    ElMessageBox.alert('您的浏览器不支持地理位置服务', '错误', {
      confirmButtonText: '确定',
      type: 'error'
    });
  }
}

// 提交表单
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      // 更新店铺信息
      newStore.value.merchantId = curMerchant.value.id // 假设商户ID为1
      newStore.value.name = ruleForm.storeName
      newStore.value.category = ruleForm.categories[0] // 主类别
      newStore.value.subCategory = ruleForm.categories[1] // 子类别
      newStore.value.tags = dynamicTags.value
      newStore.value.description = ruleForm.storeDescription
      const startTime = formatTime(ruleForm.storeOpeningTime[0]); // "10:00"
      const endTime = formatTime(ruleForm.storeOpeningTime[1]);   // "23:00"
      newStore.value.openingHours = `${startTime}-${endTime}`
      newStore.value.contactInfo = ruleForm.storeContact
      newStore.value.address = ruleForm.storeAddress
      newStore.value.longitude = storeLongitude.value;
      newStore.value.latitude = storeLatitude.value;
      newStore.value.coverImage = ruleForm.storeCover
      newStore.value.license = ruleForm.storeLicense
      newStore.value.photos = ruleForm.storePhotos
      console.log(ruleForm.storePhotos)
      newStore.value.priceMin = ruleForm.priceMin
      newStore.value.priceMax = ruleForm.priceMax
      console.log(newStore.value)
      insertANewStore(newStore.value).then(res => {
        if (res.data) {
          ElMessageBox.alert('店铺创建成功，请耐心等待审核', '提示', {
            confirmButtonText: '确定',
            type: 'success'
          }).then(() => {
            router.push({path: '/merchant/info'})
          })
        } else {
          ElMessageBox.alert('店铺创建失败，请稍后再试', '提示', {
            confirmButtonText: '确定',
            type: 'error'
          })
        }
      })
    } else {
      console.log('error submit!', fields)
      // const startTime = formatTime(ruleForm.storeOpeningTime[0]); // "10:00"
      // const endTime = formatTime(ruleForm.storeOpeningTime[1]);   // "23:00"
      // newStore.value.openingHours = `${startTime}-${endTime}`
      // console.log(newStore.value)
    }
  })
}

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}



</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <el-button
            key="back"
            type=""
            text
            @click="router.push('/merchant/storeManageList/1')"
        >
          <el-icon>
            <ArrowLeftBold/>
          </el-icon>
          <span>返回</span>
        </el-button>
        <span>填写开店信息</span>
      </div>
    </template>
    <el-form
        ref="ruleFormRef"
        style="max-width: 800px; margin: 0 auto;"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
    >
      <el-form-item label="店名" prop="storeName">
        <el-input v-model="ruleForm.storeName"/>
      </el-form-item>
      <el-form-item label="类别" prop="categories">
        <el-cascader v-model="ruleForm.categories" :options="categoriesOptions" clearable/>
      </el-form-item>
      <el-form-item label="封面" prop="storeCover">
        <el-upload
            class="avatar-uploader"
            action="/api/file/upload"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
        >
          <img
              v-if="storeCoverImageUrl"
              :src="storeCoverImageUrl"
              class="avatar"
              style="height: 100px"
              alt=""
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="标签">
        <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
            v-if="inputVisible"
            ref="InputRef"
            v-model="inputValue"
            class="w-20"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
            style="max-width: 100px"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">
          + 新标签
        </el-button>
      </el-form-item>
      <el-form-item label="营业时间" prop="storeOpeningTime">
        <div class="demo-range">
          <el-time-picker
              v-model="ruleForm.storeOpeningTime"
              is-range
              range-separator="至"
              start-placeholder="开门时间"
              end-placeholder="关门时间"
          />
        </div>
      </el-form-item>
      <el-form-item label="联系方式" prop="storeContact">
        <el-input v-model="ruleForm.storeContact"/>
      </el-form-item>
      <el-form-item label="详细地址" prop="storeAddress">
        <el-input v-model="ruleForm.storeAddress"/>
      </el-form-item>
      <el-form-item label="位置" prop="storeLocation">
        <el-button @click="getLocation">
          <el-icon>
            <Location/>
          </el-icon>
          <span>点击获取位置</span>
        </el-button>
        <span v-if="ruleForm.storeLocation">
          【当前位置：{{ruleForm.storeLocation}}】
        </span>
      </el-form-item>
      <el-form-item label="营业执照" prop="storeLicense">
        <el-upload
            class="avatar-uploader"
            action="/api/file/upload"
            :show-file-list="false"
            :on-success="handleLicenseSuccess"
        >
          <img
              v-if="storeLicenseImageUrl"
              :src="storeLicenseImageUrl"
              class="avatar"
              style="height: 100px"
              alt=""
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="店铺照片" prop="storePhotos">
        <el-image
            v-for="(url, idx) in storePhotoList"
            :key="idx"
            :src="url"
            class="store-photos"
            style="margin-right: 10px; height: 100px"
            fit="cover"
        />
        <el-upload
            class="store-photos-uploader"
            action="/api/file/upload"
            :show-file-list="false"
            :on-success="(res, file) => handlePhotoSuccess(res, file)"
        >
          <el-icon class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="最低价" prop="priceMin">
        <el-input type="number" v-model.number="ruleForm.priceMin" placeholder="最低价" class="filter-input"/>
      </el-form-item>
      <el-form-item label="最高价" prop="priceMax">
        <el-input type="number" v-model.number="ruleForm.priceMax" placeholder="最高价" class="filter-input"/>
      </el-form-item>
      <el-form-item label="店铺描述" prop="storeDescription">
        <el-input v-model="ruleForm.storeDescription" type="textarea" :rows="5"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          创建我的店铺
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">
          清空已填信息
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped lang="scss">
.header {
  display: flex;
}

.demo-range .el-date-editor {
  margin: 8px;
}

.demo-range .el-range-separator {
  box-sizing: content-box;
}

.filter-input {
  width: 100px;
}

</style>
